package com.bclz.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Service
public class FileService {
	
	//   /opt/soft/images
	@Value("${file.path}")
	private String filePath;
	
	@Value("${nginx.url}")
	private String nginxUrl;
	/**
	 * 
	 * Title: getImagePath  
	 * Description:  上传图片并获取文件路径
	 * @param files
	 * @return
	 * @throws Exception
	 */
	public String getImagePath(MultipartFile file,String openid ) throws Exception  {
		saveToLocal(file,filePath,openid);
		return nginxUrl+File.separator+"images"+File.separator+"wx_"+openid+".jpg";
	}
	
	/**
	 * 
	 * Title: saveToLocal  
	 * Description:  文件保存到本地
	 * @param file
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	private File saveToLocal(MultipartFile file,String filePath,String openid) throws Exception  {
		File newFile=new File(filePath+File.separator+"wx_"+openid+".jpg");
		if(!newFile.exists()) {
			newFile.createNewFile();
		}
		FileUtils.saveFile(file.getInputStream(), newFile);
		return newFile;
	}
	
	/**
	 * 
	 * Title: fromNetImage  
	 * Description:  从微信远程获取头像
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public  String fromNetImage(String url,String openid) throws Exception  {
		String realPath=filePath+File.separator+"wx_"+openid+".jpg";
		URL u = new URL(url);
		BufferedImage bufImage=ImageIO.read(u);
		File newFile=new File(realPath);
		if(!newFile.exists()) {
			newFile.createNewFile();
		}
		ImageIO.write(bufImage, "jpg", newFile);
		return nginxUrl+File.separator+"images"+File.separator+"wx_"+openid+".jpg";
	}
	
	/**
	 * 
	 * Title: fileExists  
	 * Description:  判断文件是否存在
	 * @param filePath
	 * @return
	 */
	public boolean fileExists(String fileName) {
		File newFile=new File(filePath+File.separator+fileName);
		return newFile.exists();
	}
	
}
